package com.dianpingmedia.wifitz.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.dianpingmedia.wifitz.WifiService;
import com.dianpingmedia.wifitz.read.listener.IReader;
import com.dianpingmedia.wifitz.read.manager.ReadManager;
import com.dianpingmedia.wifitz.read.serial.SerialPortManager;

/**
 * @author zsc
 * @create 2018/3/27 0027
 * @Describe
 */
public class UsbBroadcastReceiver extends BroadcastReceiver {
    public final static String ON_ACTION = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    public final static String OFF_ACTION = "android.hardware.usb.action.USB_DEVICE_DETACHED";
    private Handler mHandler = new Handler();
    private Handler mLogHandler;

    @Override
    public void onReceive(final Context context, Intent intent) {
        String action = intent.getAction();
        if (!TextUtils.isEmpty(action) && (ON_ACTION.equals(action) || OFF_ACTION.equals(action))) {
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            int productId = device.getProductId();
            int vendorId = device.getVendorId();
            Log.d("wifiTz", "productId=" + productId);
            Log.d("wifiTz", "vendorId=" + vendorId);
            if (productId == 60000 && vendorId == 4292) {
                if (OFF_ACTION.equals(action)) {
                    String log = "-------------------wifi探针已经移除--------------------\n";
                    Log.d("wifiTz", log);
                    sendMessage(log);
                    WifiService.mReadManager.stop();
                } else if (ON_ACTION.equals(action)) {
                    String log = "-------------------wifi探针挂载，正在努力启动-------------\n";
                    Log.d("wifiTz", log);
                    sendMessage(log);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Intent wifiServiceIntent = new Intent(context, WifiService.class);
                                context.startService(wifiServiceIntent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 2000);
                }
            }
        }
    }

    private void sendMessage(String log) {
        if (mLogHandler != null) {
            Message obtain = Message.obtain();
            obtain.what = 0;
            obtain.obj = log;
            mLogHandler.sendMessage(obtain);
        }
    }

    public void setHandler(Handler handler) {
        mLogHandler = handler;
    }
}
